package cn.zjgsu.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.jdbc.Null;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleIfStatement.Else;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.zjgsu.constant.UserConstant;
import cn.zjgsu.domain.TbCourse;
import cn.zjgsu.domain.TbCourseFile;
import cn.zjgsu.domain.TbStudent;
import cn.zjgsu.domain.TbTask;
import cn.zjgsu.domain.TbTeacher;
import cn.zjgsu.domain.TbUser;
import cn.zjgsu.exception.MyException;
import cn.zjgsu.service.ICourseService;
import cn.zjgsu.service.IStudentService;
import cn.zjgsu.service.ITaskService;
import cn.zjgsu.service.ITeacherService;
import cn.zjgsu.utils.Page;
import cn.zjgsu.utils.SHA1;

/**
 * 教师操作
 * @author 颜佳钦
 *
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {
	@Resource
	private ITeacherService teacherService;
	@Resource
	private IStudentService studentService;
	@Resource
	private ITaskService taskService;
	@Resource
	private ICourseService courseService;
	
	
	
	
	@RequestMapping("/index")
	public String index(HttpSession session,HttpServletRequest req) {

		if (session.getAttribute("user") == null)
	       return "teacher/index";
		else
			return"teacher/index";
		
	}

	/**
	 * @author 颜佳钦
	 *获取教师个人信息
	 */
	@RequestMapping("/teacherInfo")
	public String getTeacherInfo(HttpServletRequest request){
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		
		int fkUser =user.getId();
		TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);
		request.setAttribute("teacher", teacher);

		return "teacher/teacherInfo";	
	}
	
	
	/**
	 * @author 颜佳钦
	 *教师信息保存
	 */
	@RequestMapping(value = "/saveInfo", method = RequestMethod.POST)
	public String saveInfo(HttpServletRequest request, TbTeacher teacher)throws Exception{
		String strMessage;
		try{
	
        
		teacherService.updateTeacher(teacher);
		strMessage = "<script type='text/javascript'>alert('保存成功！')</script>";
			
		request.setAttribute("message", strMessage);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('保存失败！')</script>";
			 request.setAttribute("message", strMessage);
			throw new MyException("读取异常，请重新读取！");
		}
		return "forward:/teacher/teacherInfo/";
	}
	
	
	
	/**
	 * @author 颜佳钦
	 *获取教师名字并跳转到密码修改页面
	 */
	@RequestMapping("/changePasswordUI")
	public String changePasswordUI(HttpServletRequest request){
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		
		int fkUser =user.getId();
		TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);
		
		request.getSession().setAttribute("teacher",teacher);

		return "teacher/changePassword";	
	}
	
	/**
	 * @author 颜佳钦
	 *获取教师名字并跳转到密码修改页面
	 */
	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	public String changePassword(HttpServletRequest request)throws Exception{
		//TbUser user = (TbUser) request.getSession().getAttribute("user");
	   String errorold;
	   String errorChange;
	   String strMessage;
	   TbTeacher teacher=(TbTeacher) request.getSession().getAttribute("teacher");
	   String oldPassword=teacher.getTeacherPwd();
	   String inputOldPassword=request.getParameter("oldPassword");
	   String changePassword=request.getParameter("changePassword");
	   String changeRepassword=request.getParameter("changeRepassword");
	   try{
	   if(!oldPassword.equals(SHA1 .encrypt(inputOldPassword)))
	   {
		    errorold= "密码输入不正确";
		   
		   request.setAttribute("errorold",errorold);
	   }
	   else if (!changePassword.equals(changeRepassword))
	   {
		   errorChange= "两次输入的密码不一致";
		   request.setAttribute("errorChange", errorChange);
	   }
	   else{
		   
		int pkTeacher =teacher.getPkTeacher();
		
		teacherService.changeTeacherPassword(pkTeacher,changePassword);
		
		strMessage = "<script type='text/javascript'>alert('修改成功！')</script>";
		
		request.setAttribute("message", strMessage);
		
	   }
	   }catch (Exception e) {
			
			 strMessage = "<script type='text/javascript'>alert('修改密码失败！')</script>";
			 request.setAttribute("message", strMessage);
			
		}

		return "forward:/teacher/changePasswordUI/";	
	}
	
	
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取
	 */
	@RequestMapping("/singleStudentUI")
	public String singleStudentUI(HttpServletRequest request){
		String strMessage;
       TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);
		request.getSession().setAttribute("teacher", teacher);
		List<String> listAll=teacherService.getYear(teacher.getPkTeacher());
		if(listAll.isEmpty())
		{
			
		   strMessage = "<script type='text/javascript'>alert('暂时没有课程,请先添加课程！')</script>";
	       request.setAttribute("message", strMessage);
			
			
		}
		else{
		request.setAttribute("listAll", listAll);
		}
		return "teacher/studentManage/singleStudent";	
	}
	
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取
	 */
	
	@RequestMapping(value="/findCourseByYear", method = RequestMethod.POST)
	public @ResponseBody String findCourseByYear(@RequestParam String year,HttpServletRequest request){
		String strMessage;
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);
		if(year==null)
		{
			
		   strMessage = "<script type='text/javascript'>alert('暂时没有课程,请先添加课程!')</script>";
	       request.setAttribute("message", strMessage);
		  return null;	
		}
		else{
					
		List<String> listAll=teacherService.findCourseByYear(teacher.getPkTeacher(),year);	
		String data =JSONObject.toJSONString(listAll);
		
		return data; 
		}
			
	}
	
	
	/**
	 * @author 颜佳钦
	 *单个学生绑定课程
	 */
	@RequestMapping(value = "/singleStudent", method = RequestMethod.POST)
	public String singleStudent(@RequestParam String year,@RequestParam String courseName,@RequestParam String studentNum,HttpServletRequest request)throws Exception{
		String strMessage;
		try{
			TbStudent student=studentService.selectByStudentNum(studentNum);
	    if(student!=null)
	    {
	    TbTeacher teacher = (TbTeacher) request.getSession().getAttribute("teacher");
	    int fkTeacher = teacher.getPkTeacher();
	    int fkStudent=student.getPkStudent();
		teacherService.linkStudentCourse(year,courseName,fkStudent,fkTeacher);
		strMessage = "<script type='text/javascript'>alert('保存成功！')</script>";
			
		request.setAttribute("message", strMessage);
	    }
	    else
	    {
	    	
	    	strMessage = "<script type='text/javascript'>alert('该学生不存在，保存失败！')</script>";
			
			request.setAttribute("message", strMessage);

	    }
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('保存失败！')</script>";
			 request.setAttribute("message", strMessage);
		}
		return "forward:/teacher/singleStudentUI/";
	}
	
	
	
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取
	 */
	@RequestMapping("/manyStudentUI")
	public String manyStudentUI(HttpServletRequest request){
		String strMessage;
       TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);
		request.getSession().setAttribute("teacher", teacher);
		List<String> listAll=teacherService.getYear(teacher.getPkTeacher());
		if(listAll.isEmpty())
		{
			
		   strMessage = "<script type='text/javascript'>alert('暂时没有课程,请先添加课程！')</script>";
	       request.setAttribute("message", strMessage);
			
			
		}
		else{
		request.setAttribute("listAll", listAll);
		}
		return "teacher/studentManage/manyStudent";	
	}
	
	/**
	 * @author 颜佳钦
	 *多个学生绑定课程
	 */
	@RequestMapping(value = "/manyStudent", method = RequestMethod.POST)
	public String manyStudent(@RequestParam String year,@RequestParam String courseName,@RequestParam MultipartFile excelFile,HttpServletRequest request)throws Exception{
		String strMessage;
      if(excelFile==null)
	        {
				
				strMessage = "<script type='text/javascript'>alert('导入失败！')</script>";
				
				request.setAttribute("message", strMessage);
				return null;
			}
			String fileName=excelFile.getOriginalFilename();
			long size=excelFile.getSize();
			if(fileName==null || fileName.equals("") &&size==0)
			{
		       strMessage = "<script type='text/javascript'>alert('文件名为空，导入失败！')</script>";
				
				request.setAttribute("message", strMessage);
				return null;
			}
	
		try {
			InputStream in=excelFile.getInputStream();
			
		    TbTeacher teacher = (TbTeacher) request.getSession().getAttribute("teacher");
		    int fkTeacher = teacher.getPkTeacher();
			teacherService.linkStudentCourseExcel(year,courseName,fkTeacher,in,fileName);
			strMessage = "<script type='text/javascript'>alert('保存成功！')</script>";
				
			request.setAttribute("message", strMessage);
	        
		   } catch (IOException e) {
		
			 strMessage = "<script type='text/javascript'>alert('导入失败！')</script>";
				
				request.setAttribute("message", strMessage);
			throw new MyException("读取异常，请重新读取！");
		  }

		return "forward:/teacher/singleStudentUI/";
	 }
	
	
	
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取
	 */
	@RequestMapping("/courseListUI")
	public String courseListUI(HttpServletRequest request){
		String strMessage;
       TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);
		request.getSession().setAttribute("teacher", teacher);
		List<String> listAll=teacherService.getYear(teacher.getPkTeacher());
		if(listAll.isEmpty())
		{
			
		   strMessage = "<script type='text/javascript'>alert('暂时没有课程,请先添加课程！')</script>";
	       request.setAttribute("message", strMessage);
			
			
		}
		else{
		request.setAttribute("listAll", listAll);
		}
		return "teacher/courseManage/courseList";	
	}
	
	
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取
	 */
	
	@RequestMapping(value="/findCourseRecordByYear", method = RequestMethod.POST)
	public @ResponseBody String findCourseRecordByYear(@RequestParam String year,HttpServletRequest request){
		String strMessage;
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);
		if(year==null)
		{
			
		   strMessage = "<script type='text/javascript'>alert('暂时没有课程,请先添加课程!')</script>";
	       request.setAttribute("message", strMessage);
		  return null;	
		}
		else{
					
		List<TbCourse> listAll2=teacherService.findCourseRecordByYear(teacher.getPkTeacher(),year);	
	
		String data =JSONObject.toJSONString(listAll2);
		return  data;
		}
			
	}
	
	
	/**
	 * @author 颜佳钦
	 *获取教师个人任务列表并且跳转到个人日历页面
	 */
	@RequestMapping("/taskManage")
	public String getTaskList(HttpServletRequest request){
		String pageNow = request.getParameter("pageNow");
		Page page=null;
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		List<TbTask>  listAll=new ArrayList<TbTask>();
		int totalCount=teacherService.getTaskCount(fkUser);

		if(totalCount!=0){
			if(pageNow!=null){
				page=new Page(totalCount,Integer.parseInt(pageNow));
				listAll=teacherService.selectByPage(page.getStartPos(),page.getPageSize(),fkUser);
			}else{
				page=new Page(totalCount, 1);
			
				listAll=teacherService.selectByPage(page.getStartPos(),page.getPageSize(),fkUser);
			}
		}
		request.setAttribute("page", page);
		request.setAttribute("listAll", listAll);

		return "teacher/taskManage/taskList";	
	}
	
	
	/**
	 * @author 颜佳钦
	 *教师个人日历添加
	 */
	@RequestMapping(value = "/taskManage/taskImport", method = RequestMethod.POST)
	public String taskImport(HttpServletRequest request, TbTask task)throws Exception{
		String strMessage;
		try{
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		task.setFkUser(fkUser);

		taskService.addTask(task);
		strMessage = "<script type='text/javascript'>alert('添加成功！')</script>";
			
		request.setAttribute("message", strMessage);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('添加失败！')</script>";
			 request.setAttribute("message", strMessage);
			
		}
		return "forward:/teacher/taskManage";
	}
	
	
	
	/**
	 * @author 颜佳钦
	 *教师个人日历添加
	 */
	@RequestMapping(value = "/taskManage/taskImportJs", method = RequestMethod.POST)
	@ResponseBody
	public String taskImportJs(HttpServletRequest request, TbTask task)throws Exception{
		String strMessage;
		try{
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		task.setFkUser(fkUser);

		taskService.addTask(task);
		strMessage = "<script type='text/javascript'>alert('添加成功！')</script>";
			
		request.setAttribute("message", strMessage);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('添加失败！')</script>";
			 request.setAttribute("message", strMessage);
			
		}
		return "ok";
	}
	
	
	
	/**
	 * @author 颜佳钦
	 *个人日历的删除
	 */
	@RequestMapping("/taskManage/deleteTask/{pkTask}")
	public String deleteTask(@PathVariable("pkTask") int pkTask,HttpServletRequest request)throws Exception{
		
		String strMessage;
		try{
			
			taskService.deleteTask(pkTask);
			 strMessage = "<script type='text/javascript'>alert('删除成功！')</script>";
				
				request.setAttribute("message", strMessage);
		}
		catch(Exception e){
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('删除失败！')</script>";
				
				request.setAttribute("message", strMessage);
			throw new MyException("删除失败");
		}
		
		return "forward:/teacher/taskManage";
	}
	
	
	
	
    /**
	 * @author 颜佳钦
	 *教师提纲上传
	 */
	@RequestMapping("/importCoursePoint")
	public String importCoursePoint(HttpServletRequest request,MultipartFile excelFile,int pkCourse) throws Exception{
	
		String strMessage;
		TbCourse course=courseService.findCourseById(pkCourse);
		
		String courseName=course.getCourseName();
		
		 String filepath = "D://CoursePointUpload/";
		 File file = new File(filepath);
		//判断上传文件的保存目录是否存在
		if (!file.exists() && !file.isDirectory()) {
			strMessage = "<script type='text/javascript'>alert('目录不存在，需要创建！')</script>";
			
			request.setAttribute("message", strMessage);

		//创建目录
		file.mkdir();
		}
		
		if(excelFile==null){
			
			strMessage = "<script type='text/javascript'>alert('导入失败！')</script>";
			
			request.setAttribute("message", strMessage);

		}
		String fileName = excelFile.getOriginalFilename();
		long size = excelFile.getSize();
		//获取尾追
		String suffix=fileName.substring(fileName.lastIndexOf("."), fileName.length());
		if(!suffix.equals(".xls")&&!suffix.equals(".xlsx")||fileName==null || fileName.equals("") &&size==0){
	       strMessage = "<script type='text/javascript'>alert('非有效文件，导入失败！')</script>";
			
			request.setAttribute("message", strMessage);
		
		}
	
		try {
			String changedFileName =pkCourse+courseName+suffix;
			
			String fileAddress =filepath+changedFileName;
		
			File thefile = new File(fileAddress);
			

			if(thefile.exists())
			{
				thefile.delete();
				
			    strMessage = "<script type='text/javascript'>alert('上传失败,同名文件已存在，请删除同名文件再上传！')</script>";
					
			    request.setAttribute("message", strMessage);
			}
			else
			{
				
			excelFile.transferTo(thefile);
			
			TbCourse course2 = new TbCourse();
			
			course2.setPkCourse(pkCourse);
			course2.setCoursePointName(changedFileName);	
			course2.setCoursePointAddress(fileAddress);
	
		     courseService.importCoursePoint(course2);
		    
	        strMessage = "<script type='text/javascript'>alert('导入成功！')</script>";
			
			request.setAttribute("message", strMessage);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('导入失败！')</script>";
				
				request.setAttribute("message", strMessage);
			throw new Exception("读取异常，请重新读取！");
		}
		return "forward:/teacher/courseListUI";
	}
	
	
	/**
	 * @author 颜佳钦
	 *课表文件的下载
	 */
	@RequestMapping("/courseManage/download")
	public String downloadCourse(@RequestParam("pkCourse") int pkCourse,HttpServletRequest request, HttpServletResponse response)throws Exception{
		
		    String strMessage;
	
			TbCourse course =courseService.findCourseById(pkCourse);
			
			 File thefile =new File(course.getCoursePointAddress());
			 
			 if(thefile.exists())
			 {
				    String fileName = course.getCoursePointName().toString(); // 文件的默认保存名
				    //解决文件名中文乱码问题
				    if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
				    	fileName = URLEncoder.encode(fileName, "UTF-8");  
				    } else {  
				    	fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");  
				    }  
			        // 读到流中
			        InputStream inStream = new FileInputStream(course.getCoursePointAddress());// 文件的存放路径
			        // 设置输出的格式
			        response.reset();
			        response.setContentType("bin");
			        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName+ "\"");
			        // 循环取出流中的数据
			        byte[] b = new byte[100];
			        int len;
			        try {
			            while ((len = inStream.read(b)) > 0)
			                response.getOutputStream().write(b, 0, len);
			            inStream.close();
			          }
			        catch(Exception e){
						// TODO Auto-generated catch block
						 strMessage = "<script type='text/javascript'>alert('下载失败！')</script>";
							
							request.setAttribute("message", strMessage);
						throw new MyException("下载失败");
					}
			 }
			  else
			        {
			        	
				  strMessage = "<script type='text/javascript'>alert('暂无文件上传，请先上传！')</script>";
					
					request.setAttribute("message", strMessage);	
			        	
			        	
			        	
			        }
		
		
		
		return "forward:/teacher/courseListUI";
	}
	/**
	 * @author 颜佳钦
	 *课程提纲的删除
	 */
	@RequestMapping("/courseManage/deleteFile")
	public String deleteCourseFile(@RequestParam("pkCourse") int pkCourse,HttpServletRequest request)throws Exception{
		
		String strMessage;
		try{
			TbCourse course =courseService.findCourseById(pkCourse);
			
			 File thefile =new File(course.getCoursePointAddress());
			 if(thefile.exists())
				{
				    thefile.delete();
				}
			
			courseService.deleteCoursePoint(pkCourse);
			 strMessage = "<script type='text/javascript'>alert('删除成功！')</script>";
				
				request.setAttribute("message", strMessage);
		}
		catch(Exception e){
			// TODO Auto-generated catch block
			 strMessage = "<script type='text/javascript'>alert('删除失败！')</script>";
				
				request.setAttribute("message", strMessage);
			throw new MyException("删除失败");
		}
		
		return "forward:/teacher/courseListUI";
	}
	
	
	
	
	
	/**
	 * @author 颜佳钦
	 *获取课表年份，然后获取
	 */
	
	@RequestMapping(value="/taskShow", method = RequestMethod.POST)
	@ResponseBody//这个注解就是用来异步返回json数据，不用在http中跳转路径
	public  String taskShow(HttpServletRequest request){
	
		TbUser user = (TbUser) request.getSession().getAttribute("user");
		int fkUser =user.getId();
		/*TbTeacher teacher =teacherService.getTeacherByFkUser(fkUser);*/
					
		List<TbTask> listAll2=taskService.findTask(fkUser);	
	
		String data =JSONObject.toJSONString(listAll2);
		return  data;
		}
			
	}
	
	

